package com.flex.showdoc4j.generator.commit;

import com.flex.showdoc4j.generator.SdkFile;
import com.flex.showdoc4j.model.GeneratorSdkConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.http.client.utils.DateUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * 提交到本地目录
 * @author ganlt
 * @since 2019/10/25 10:13
 */
@Slf4j
public class LocalCommitSdk implements CommitSdk {

    @Override
    public boolean commit(GeneratorSdkConfig config, List<SdkFile> sdkFileList) {
        for (SdkFile sdkFile : sdkFileList ) {
            log.info("----------------准备提交文件:{}",sdkFile.getFileName());
            String flag = DateUtils.formatDate(new Date(), "YYYYMMddHHmmss");
            String fileDir = config.getConfigModel().getSaveDir()+File.separator+config.getPath()+"-"+flag;
            File outFile = new File(fileDir);
            if (!outFile.exists()) {
                try {
                    FileUtils.forceMkdir(outFile);
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
            File file = sdkFile.toFile(fileDir);
            String body = sdkFile.getBody();
            try {
                FileUtils.writeStringToFile(file,body, StandardCharsets.UTF_8);
            } catch (IOException e) {
                e.printStackTrace();
                log.info("-----------------提交文件:{}失败",sdkFile.getFileName());
                return false;
            }

            log.info("-----------------提交文件:{}成功",sdkFile.getFileName());
        }

        return true;
    }
}
